package com.yh.correct.controller;

import com.yh.common.utils.DateUtils;
import com.yh.correct.model.CommunityAdminMain;
import com.yh.correct.model.Page;
import com.yh.correct.model.ResultData;
import com.yh.correct.service.ICommunityAdminMainService;
import com.yh.correct.service.impl.InterviewPersonnelServiceImpl;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

/**
 * Created by comcn155 on 2017-03-08.
 *
 * 描述:社区刑人员管理控制器
 */

@RestController
@RequestMapping("/cAdminMain")
@PropertySource(value = "classpath:config/system.properties")
public class CommunityAdminMainController {

    private static Logger logger = LogManager.getLogger(CommunityAdminController.class);
    @Autowired
    private ICommunityAdminMainService camsi;
    @Value("${saveDire}")
    private String saveDire;
    @Autowired
    private InterviewPersonnelServiceImpl iipl;

    /**
     * 进入档案详情页
     * @return
     */
    @RequestMapping("/page")
    public ModelAndView page(){
        return new ModelAndView("community/communityAdminMain");
    }


    /**
     * 作者：comcn155
     * 创建时间:2017-03-11
     * 描述: 查询所有社区刑人员
     * @throws Exception
     */
    @RequestMapping("/get")
    public ResultData get(String name, String papersnum, int pageSize, int pageNum) throws Exception {
        Map<String, Object> cont = new HashMap<String, Object>();
        cont.put("pageSize", pageSize);
        cont.put("pageNum", pageNum);
        if (name == null) {
            name = "";
        }
        if (papersnum == null){
            papersnum = "";
        }
        cont.put("name", name);
        cont.put("papersnum",papersnum);
        Page p = camsi.getLikeAdminMainCount(cont);
        ResultData rd = new ResultData();
        if (p != null) {
            List<Object> e = new ArrayList();
            e.add(p);
            rd.setCode(0);
            rd.setMessage("查询成功！");
            rd.setData(e);
        }
        logger.debug(cont.get("papersnum"));
        return rd;
    }

    /**
     * 作者：comcn155
     * 创建时间:2017-03-08
     * 描述:根据id删除社区刑人员
     * @throws Exception
     */
    @RequestMapping("/del")
    public ResultData del(int id) throws Exception {
        CommunityAdminMain cam = new CommunityAdminMain();
        cam.setId(id);
        int i = camsi.delCommunityAdminMain(cam);
        ResultData rd = new ResultData();
        if (i > 0) {
            rd.setCode(0);
            rd.setMessage("删除成功！");
        } else {
            rd.setCode(-1);
            rd.setMessage("删除失败！");
        }
        return rd;
    }

    /**
     * 作者：comcn155
     * 创建时间:2017-03-12
     * 描述:根据id查询详情
     * @throws Exception
     */
    @RequestMapping("/getId")
    public ModelAndView get(int id,String sort) throws Exception{
        CommunityAdminMain cam = new CommunityAdminMain();
        cam.setId(id);
        List<Object> list = iipl.getAllCorr();
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("corr",list);
        map.put("currtime",DateUtils.getYMD());
        Map cab = camsi.getCommunityAdminMain(cam);
        map.put("cab",cab);
        logger.debug("cab的值"+cab);
        if ("editMain".equals(sort)){
            return new ModelAndView("community/editMain", map);
        }
        return new ModelAndView("community/listMain", cab);

    }

    /**
     * 作者：comcn155
     * 创建时间:2017-03-14
     * 描述:下载档案
     * @throws Exception
     */
    @RequestMapping("/down")
    public void down(String filename,int id, HttpServletResponse resp) throws Exception {
        logger.debug(saveDire +id+"\\"+ filename);
        // 设置ContentType
        resp.setContentType("application/octet-stream; charset=utf-8");
        // 处理中文文件名中文乱码问题
        // String fileName = new String(file.getName().getBytes("utf-8"),
        // "ISO-8859-1");
        resp.setHeader("Content-Disposition", "attachment; filename=" + filename);
        try {
            IOUtils.copy(new FileInputStream(new File(saveDire+"\\"+id, filename)), resp.getOutputStream());
            CommunityAdminMain cam = new CommunityAdminMain();
            cam.setId(id);
            cam.setDowload_date(new Date());
            camsi.update(cam);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 作者：comcn155
     * 创建时间:2017-03-14
     * 描述:添加档案
     * @throws Exception
     */
    @RequestMapping("/upload")
    public void upload(List<MultipartFile> files, CommunityAdminMain cam, String name) throws Exception{
        logger.debug(files);
        Integer id = camsi.getLastId();
        logger.debug(id);
        logger.debug(cam.getRecord_date());
        List<String> obj = new ArrayList<String>();
        File fe = new File(saveDire+"\\"+id+"\\");  //上传路径
        if(!fe.exists()){  //判断路径是否存在t
            fe.mkdir();
        }
        for(MultipartFile a:files){
            try {
                if(!a.isEmpty()){ /*comcn155*/
                a.transferTo(new File(fe,a.getOriginalFilename()));//a.getOriginalFilename()取文件名
                logger.debug(a.getOriginalFilename());
                obj.add(a.getOriginalFilename());
                } else {
                    obj.add("空");
                }
            } catch (IllegalStateException | IOException e) {
                e.printStackTrace();
            }
        }
        logger.debug(obj);
        cam.setTm1(obj.get(0));
        cam.setTm2(obj.get(1));
        cam.setTm3(obj.get(2));
        cam.setTm4(obj.get(3));
        cam.setTm5(obj.get(4));
        cam.setTm6(obj.get(5));
        cam.setTm7(obj.get(6));
        cam.setTm8(obj.get(7));
        cam.setTm9(obj.get(8));
        cam.setTm10(obj.get(9));
        cam.setTm11(obj.get(10));
        cam.setTm12(obj.get(11));
        cam.setTm13(obj.get(12));
        cam.setTm14(obj.get(13));
        cam.setTm15(obj.get(14));
        cam.setTm16(obj.get(15));
        cam.setTm17(obj.get(16));
        camsi.addCommunityAdminMain(cam);

        logger.debug(cam.getTm1()+cam.getTm2()+cam.getTm3()+cam.getTm16());
    }

    /**
     * 作者：comcn155
     * 创建时间:2017-03-14
     * 描述:修改档案
     * @throws Exception
     */
    @RequestMapping("/uploadEditMain")
    public void uploadEdit(List<MultipartFile> files,CommunityAdminMain ca,String name) throws Exception{
        logger.debug(files);
        Integer id = camsi.getLastId();
        logger.debug(id);
        logger.debug(ca.getRecord_date());
        logger.debug(ca.getRoot_in());
        List<String> obj = new ArrayList<String>();
        File fe = new File(saveDire+"\\"+id+"\\");  //上传路径
        if(!fe.exists()){  //判断路径是否存在
            fe.mkdir();
        }
        for(MultipartFile a:files){
            try {
                if (!a.isEmpty()){
                    a.transferTo(new File(fe,a.getOriginalFilename()));//a.getOriginalFilename()取文件名
                    logger.debug(a.getOriginalFilename());
                    obj.add(a.getOriginalFilename());
                } else {
                    obj.add("空");
                }
            } catch (IllegalStateException | IOException e) {
                e.printStackTrace();
            }
        }
        logger.debug(obj);
        ca.setTm1(obj.get(0));
        ca.setTm2(obj.get(1));
        ca.setTm3(obj.get(2));
        ca.setTm4(obj.get(3));
        ca.setTm5(obj.get(4));
        ca.setTm6(obj.get(5));
        ca.setTm7(obj.get(6));
        ca.setTm8(obj.get(7));
        ca.setTm9(obj.get(8));
        ca.setTm10(obj.get(9));
        ca.setTm11(obj.get(10));
        ca.setTm12(obj.get(11));
        ca.setTm13(obj.get(12));
        ca.setTm14(obj.get(13));
        ca.setTm15(obj.get(14));
        ca.setTm16(obj.get(15));
        ca.setTm17(obj.get(16));
        logger.info(ca.toString());
        camsi.editCommunityAdminMain(ca);
    }

    /**
     * 作者：comcn155
     * 创建时间:2017-03-14
     * 描述:查询所有矫正人员
     * @throws Exception
     */
    @RequestMapping("/addMain")
    public ModelAndView getAll() throws Exception{
        List<Object> list = iipl.getAllCorr();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("currtime", DateUtils.getYMD());
        map.put("corr", list);
        return new ModelAndView("community/addMain",map);
    }

    /**
     * @author comcn155 修改controller
     * @return
     * @throws Exception
     */
    @RequestMapping("/editMain")
    public ModelAndView edit(CommunityAdminMain ca) throws Exception{

        //casi.editCommunityAdmin(ca);
        List<Object> list = iipl.getAllCorr();
        Map listId= camsi.getCommunityAdminMain(ca); /*comcn155 查询行号*/
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("corr",list);
        map.put("currtime",DateUtils.getYMD());
        map.put("listId",listId);
        logger.info("修改档案记录id="+ca.toString());
        return new ModelAndView("community/editMain",map);
    }
}
